package com.intelligentmeterreadingsys.waterlist.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;

import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;

import com.intelligentmeterreadingsys.waterlist.copywater.activity.CopyWaterRFIDActivity;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.CopyWaterUploadActivity;
import com.intelligentmeterreadingsys.waterlist.db.WaterListDaoImpl;
import com.intelligentmeterreadingsys.waterlist.querywaterlist.activity.OneKeyUploadActivity;
import com.intelligentmeterreadingsys.waterlist.querywaterlist.activity.QueryWaterListActivity;


import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;

import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;

/**
 * 表册管理
 * @author king
 *
 */
public class WaterListMainActivity extends Activity implements OnClickListener{
	
	public Button button1;//抄表
	
	public Button button2;//表册查询
	
	public Button button3;//无线上报
	
	public Button button4;//任务单
	
	public Button button5;//抄表数据复查
	
	public int watertotal=0;
	

	
	public WaterListDaoImpl dao=null;
	
	public SharedPreferenceUtil sp=null;
	
	 private final static int DIALOG=1;
	 
	 public boolean isSafe=false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.waterlistmain);
		inti();
				
	}
     
	/**
	 * 初始化控件并注册点击监听事件
	 */
	
	public void inti(){
		sp=new SharedPreferenceUtil(this);
		isSafe=sp.getBoolean(XmlNameHelper.isSafe);
		button1=(Button)findViewById(R.id.writewater);
		button2=(Button)findViewById(R.id.querywaterlist);
		button3=(Button)findViewById(R.id.wirelessupload);
		button4=(Button)findViewById(R.id.tasklist);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
	
			
	}

	/**
	 * 添加点击事件
	 */
	@Override
	public void onClick(View v) {
		Intent intent=null;
		switch (v.getId()) {
		case R.id.writewater:
			 SharedPreferenceUtil sh=new SharedPreferenceUtil(WaterListMainActivity.this);
			 isSafe=sh.getBoolean(XmlNameHelper.isSafe);
			 if(isSafe){
				 intent=new Intent(WaterListMainActivity.this, CopyWaterRFIDActivity.class);
				 startActivity(intent);
			 }else{
				 showDialog(CopyWaterRFIDActivity.class);
			 }
			
			 
			break;
		case R.id.querywaterlist:
			intent=new Intent(this, QueryWaterListActivity.class);
			startActivity(intent);
			break;
		case R.id.wirelessupload:
			intent=new Intent(this,CopyWaterUploadActivity.class);
			startActivity(intent);
			break;
		case R.id.tasklist:
			WaterListDaoImpl dao=new WaterListDaoImpl(this);
			int number=dao.queryNoUpload();
			int townumber=dao.queryTowCopy();
			dao.close();
			if(number>0){
				Toast.makeText(WaterListMainActivity.this, "你还有没上的表册，不能下载", 1000).show();
				return;
			}
			if(townumber>0){
				showDialog(DIALOG);
			}else{
				showDialog(DIALOG+1);
			}
			
			
			break;
		
		default:
			break;
		}
		
	}
	
	
	public class download extends AsyncTask<String, Integer, String>{
		
		public HttpClientServer server;
		
		public ProgressDialog dialog;
		
		public download(ProgressDialog dialog){
			this.dialog=dialog;
		}
		

		@Override
		protected String doInBackground(String... params) {

			  String userid=sp.getValue(XmlNameHelper.IMSI);
			 
			  Map<String, String> map=new HashMap<String, String>();
			  map.put("imsi", userid);
			   String response=  server.doPost(map, params[0]);
			   System.out.println(response);
			   if(!response.equals("error")){
				   try {
					JSONObject obj=new JSONObject(response);
					//水表信息
					JSONArray waterinfo=obj.getJSONArray("waterinfo");
					
					int a=watertotal=waterinfo.length();
					//表册信息
					JSONArray waterlist=obj.getJSONArray("tlps");
					int b=waterlist.length();
					//用户信息
					JSONArray userinfo=obj.getJSONArray("userinfo");
					int c=userinfo.length();
					//月用水量信息
					JSONArray usewater=obj.getJSONArray("usewaterinfo");
					//工程单类型
					JSONArray ordertype=obj.getJSONArray("typeinfo");
					int d=usewater.length();
					int total=a+b+c+d;
		           publishProgress(total);	
		           
					List<ContentValues> listwaterinfo=new ArrayList<ContentValues>();
					
					if(waterinfo!=null&&waterinfo.length()>0){
						for(int i=0;i<waterinfo.length();i++){
							JSONObject jb=waterinfo.getJSONObject(i);
							ContentValues value=new ContentValues();
							value.put("waternumber", jb.getString("waternumber"));
							value.put("waterlistid", jb.getString("waterlistid"));
							value.put("usernumber", jb.getString("usernumber"));
							value.put("wateradds", jb.getString("wateradds"));
							if(jb.getString("alarmlimit").equals("null")){
								value.put("alarmlimit", 0.0);
							}else{
								value.put("alarmlimit", jb.getDouble("alarmlimit"));
							}
						
							if(jb.getString("lowalarmlimit").equals("null")){
								value.put("lowalarmlimit", 0.0);
							}else{
								value.put("lowalarmlimit", jb.getDouble("lowalarmlimit"));
							}
							
							
							String latitude=jb.getString("latitude");
							String rfidnumber=jb.getString("RFIDnumber");
							if(!rfidnumber.equals("null")){
								value.put("RFIDnumber", jb.getString("RFIDnumber"));
							}
							if(rfidnumber.equals("null")&&latitude.equals("null")){
								value.put("bandingstatus", "2");
							}else{
								value.put("bandingstatus", "3");
							}
							
							if(!latitude.equals("null")){
								value.put("latitude", jb.getDouble("latitude"));
							}
							String longitude=jb.getString("longitude");
							if(!longitude.equals("null")){
								value.put("longitude", jb.getDouble("longitude"));
							}
							String lastmonthwater=jb.getString("lastmonthwater");
							System.out.println(lastmonthwater+"------------");
							if(!lastmonthwater.equals("null")){
								
								value.put("lastmonthwater", jb.getDouble("lastmonthwater"));
							}else{
								value.put("lastmonthwater", 0.0);
							}
							
							value.put("metercaliber", jb.getString("metercaliber"));
							if(jb.getString("lastdate").equals("null")){
								value.put("lastdate", "第一次抄");
							}else{
								value.put("lastdate", jb.getString("lastdate"));
							}
							
							value.put("iscopystatus", "未抄");
							value.put("isupload", "0");	
							value.put("ismultiplecopy", "0");
							value.put("waterproperties", jb.getString("waterproperties"));
							value.put("locationadds", jb.getString("addr"));
							
							
							listwaterinfo.add(value);
							publishProgress(i+1);
							System.out.println("水表信息");
						}
						
					}
					
					List<ContentValues> listuserinfo=new ArrayList<ContentValues>();
					if(userinfo!=null&&userinfo.length()>0){
						for(int i=0;i<userinfo.length();i++){
							JSONObject jb=userinfo.getJSONObject(i);
							ContentValues value=new ContentValues();
							value.put("username", jb.getString("name"));
							value.put("usernumber", jb.getString("number"));
							value.put("phone", jb.getString("phone"));
							value.put("useradds", jb.getString("adds"));
							value.put("usertype", jb.getString("usertype"));
							value.put("userstatus", jb.getString("status"));
							value.put("ismultiplecopy", "0");
							listuserinfo.add(value);
							publishProgress(a+i+1);
						}
					}
					
					
					List<ContentValues> listusewater=new ArrayList<ContentValues>();
					if(usewater!=null&&usewater.length()>0){
						for(int i=0;i<usewater.length();i++){
							JSONObject js=usewater.getJSONObject(i);
							 ContentValues value=new ContentValues();
							 value.put("waternumber",js.getString("waternumber") );
							 value.put("month", js.getString("month"));
							 if(js.getString("watercount").equals("null")){
								 value.put("watercount",0);
							 }else{
								 value.put("watercount", js.getString("watercount"));
							 }
							 value.put("ismultiplecopy", "0");
							 listusewater.add(value);
							 publishProgress(a+c+i+1);
						}
					}
					
					
					List<ContentValues> listwaterlist=new ArrayList<ContentValues>();
					if(waterlist!=null&&waterlist.length()>0){
						for(int i=0;i<waterlist.length();i++){
							JSONObject js=waterlist.getJSONObject(i);
							ContentValues value=new ContentValues();
							value.put("number", js.getString("tbl_id"));
							value.put("name", js.getString("tbl_name"));
						
							listwaterlist.add(value);
							publishProgress(a+b+c+i+1);
							
						}
					}
					
				
					List<ContentValues> listordertype=new ArrayList<ContentValues>();
					if(ordertype!=null&&ordertype.length()>0){
						for(int i=0;i<ordertype.length();i++){
							JSONObject json=ordertype.getJSONObject(i);
							ContentValues value=new ContentValues();
							value.put("name", json.getString("name"));
							value.put("number", json.getString("number"));
							value.put("status", "2");
							listordertype.add(value);
						}
					}
					
					dao.insertALL(listordertype, DbTableName.TYPE);
					boolean b1=false;
					b1=dao.insertALL(listwaterlist, DbTableName.WATERLIST);
					if(b1){
						b1=dao.insertALL(listuserinfo, DbTableName.USERINFO);
						if(b1){
							b1=dao.insertALL(listusewater, DbTableName.USEWATERINFO);
							if(b1){
								b1=dao.insertALL(listwaterinfo, DbTableName.WATERINFO);
							}
						}
					}
					
					dao.close();
					if(b1){
					
						return "success";
					}else{
					
						return "error";
					}
				} catch (JSONException e) {
					dao.close();
					System.out.println(e);
					e.printStackTrace();

					
				}
				   
			   }
			return "error";
			  
		  
		}

		@Override
		protected void onPreExecute() {
			server=new HttpClientServer(WaterListMainActivity.this);
			dao=new WaterListDaoImpl(WaterListMainActivity.this);
			
			dialog.setMax(100);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setTitle("下载数据中.......");
			dialog.setCancelable(false);
			dialog.show();
			
		}

	

		@Override
		protected void onProgressUpdate(Integer... values) {					    
			dialog.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			dao.close();
			dialog.cancel();
			System.out.println("result:"+result);
			if(TextUtils.isEmpty(result)){
				Toast.makeText(WaterListMainActivity.this, "下载失败", Toast.LENGTH_LONG).show();
			}else if(result.equals("error")){
				Toast.makeText(WaterListMainActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
			}
			else{
				Toast.makeText(WaterListMainActivity.this, "下载成功,共下载抄表数据:"+watertotal, Toast.LENGTH_LONG).show();
			}
			
			
		}
		
		
	}
	
	
	      
	  /**
	   * 下载后返回给服务器标志
	   * @param message
	   * @return
	   */
	      public boolean Respon(String message){
	    	  boolean b=false;
	    	  HttpClientServer server=new HttpClientServer(this);
	    	  String userid=sp.getValue("userid");
	    	  Map<String, String> maps=new HashMap<String, String>();
				maps.put("userid", userid);
				maps.put("message", message);
				String s=server.doPost(maps, RequestUrl.DownloadWaterList);
				if(!s.equals("error")){
					b=true;
				}
				return b;
	      }
	      
	     @Override
	  	protected Dialog onCreateDialog(int id) {
	  		 Dialog dialog=null;
	  	        switch (id) {
	  	        case DIALOG:
	  	            Builder builder=new android.app.AlertDialog.Builder(this);
	  	            //设置对话框的图标
	  	            builder.setIcon(R.drawable.buttondraw);
	  	            //设置对话框的标题
	  	            builder.setMessage("你有标注的二次抄表哟！确定将下载新的表册！");
	  	             
	  	            
	  	            //添加一个确定按钮
	  	            builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	  	                public void onClick(DialogInterface dialog, int which) {
	  	                	dao=new WaterListDaoImpl(WaterListMainActivity.this);
	  	                	dao.delectWaterList();
	  	                	dao.close();
	  	                	FileNameUtil fi=new FileNameUtil(WaterListMainActivity.this);
	  	                	fi.delectFile("waterimage");
	  	                	 ProgressDialog pd=new ProgressDialog(WaterListMainActivity.this);
	  	         		  
	  	       			download d=new download(pd);
	  	       			d.execute(RequestUrl.DownloadWaterList);
	  	                }
	  	            });

                    builder.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
 					
 					@Override
 					public void onClick(DialogInterface dialog, int which) {
 						
 						
 					}
 				});
	  	            //创建一个单选按钮对话框
	  	            dialog=builder.create();
	  	            break;
	  	        case DIALOG+1:
	  	        	 Builder builder1=new android.app.AlertDialog.Builder(this);
	              //设置对话框的图标
	                     builder1.setIcon(R.drawable.buttondraw);
	                     builder1.setMessage("确定下载新表册？");
	                     builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
	  					
	  					@Override
	  					public void onClick(DialogInterface dialog, int which) {						 

	  	                	dao=new WaterListDaoImpl(WaterListMainActivity.this);
	  	                	dao.delectWaterList();
	  	                	dao.close();
	  	                	FileNameUtil fi=new FileNameUtil(WaterListMainActivity.this);
	  	                	fi.delectFile("waterimage");
	  	                	 ProgressDialog pd=new ProgressDialog(WaterListMainActivity.this);
	  	         		  
	  	       			download d=new download(pd);
	  	       			d.execute(RequestUrl.DownloadWaterList);
	  	                	  					
	  					}
	  				});
	                     builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
	  					
	  					@Override
	  					public void onClick(DialogInterface dialog, int which) {
	  						
	  						
	  					}
	  				});
	                     //创建一个单选按钮对话框
	     	            dialog=builder1.create();
	     	            break;
	  	        }
	  	        return dialog;
	  	}
	     
	     public boolean showDialog(final Class<?> activityClass){
	         
	  	   LayoutInflater factory = LayoutInflater.from(this);  
	         final View textEntryView = factory.inflate(R.layout.dialog, null);  
	         final EditText editTextPass = (EditText) textEntryView.findViewById(R.id.txt_password);  
	           
	         AlertDialog.Builder ad1 = new AlertDialog.Builder(this);  
	         ad1.setIcon(android.R.drawable.ic_dialog_info);  
	         ad1.setView(textEntryView);
	         ad1.setTitle("安全验证");
	         ad1.setPositiveButton("确定", new  android.content.DialogInterface.OnClickListener() {
	  		
	  		@Override
	  		public void onClick(DialogInterface dialog, int which) {
	  			String pass=editTextPass.getEditableText().toString();
	  			SharedPreferenceUtil sh=new SharedPreferenceUtil(WaterListMainActivity.this);
	  			if(pass.equals(sh.getValue(XmlNameHelper.passWord))){
	  				isSafe=true;
	  				Intent intents=new Intent(WaterListMainActivity.this, activityClass);
	  				startActivity(intents);
	  				
	  			}else{
	  				Toast.makeText(WaterListMainActivity.this, "密码错误", 1000).show();
	  				isSafe=false;
	  			}
	  			
	  		}
	  	});
	         ad1.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
	  		
	  		@Override
	  		public void onClick(DialogInterface dialog, int which) {
	  		       isSafe=false;
	  			
	  		}
	  	});
	         ad1.create();
	         ad1.show();
			return isSafe;

	     }
	     
	    
}
